<template>
  <div class="c-fieldList flex">
    <Menu :active-name="fIndex" @on-select="onSelect" width="auto">
      <vuedraggable v-model="curProperty[category]">
      <MenuItem v-for="(item, i) in curProperty[category]" :name="i" :key="i">
       <p>{{getFieldLabel(curProperty[category][i])}}</p>
       <p class="itemflag">
         <span class="hiddenItem" 
           v-if="curProperty[category][i].length && !curProperty[category][i][0].defaultValue"></span>
         <span class="selectItem" 
           v-if="curProperty[category][i].length>3 && curProperty[category][i][3].defaultValue==='select'"></span>
         <span class="cusItem" 
           v-if="curProperty[category][i].length>3 && curProperty[category][i][3].defaultValue.indexOf('cus') === 0"></span>
       </p>
      </MenuItem>
      </vuedraggable>
    </Menu>
    <Table ref="table" :columns="columns" :data="curField" slot="content" style="flex:1;">
      <template slot-scope="{ row, index }" slot="defaultValue">
        <fieldCell
            v-if="refresh"
            v-model="curField[index].defaultValue"
            :compGroup="compGroup"
            :config="{
              ...curField[index],
              key: curField[index].name,
              editor: curField[index].valueType,
              clearable: true,
              filterable: true,
              options: getOptions(curField[index]),
            }"
            @change="updateRow(fIndex,curField[index].name,$event)"
        ></fieldCell>
      </template>
      <template slot-scope="{ row, index }" slot="showField">
        <Checkbox v-model="curField[index].showField"></Checkbox>
      </template>
    </Table>
    <!-- <Collapse :v-model="tableIndex" accordion>
      <vuedraggable v-model="curProperty[category]">
      <Panel >
        <Div :gutter="2" style="display:inline-flex;align-items: center">
          <span>{{`${$t(`compDesign.jProperty.fieldAttr`)}: ${curField.find(item=>item.name==='dataIndex').defaultValue}`}}</span>
        </Div>

      </Panel>
      </vuedraggable>
    </Collapse> -->
  </div>
</template>

<script>
    import fieldCell from './fieldCell';
    import storeVar from '../../mixins/storeVar';
    import vuedraggable from "vuedraggable"
    import {mapActions, mapState} from "vuex";
    import { filedTypeOption, ruleTplOption } from "public/starLib/components/config/tpl"

    export default {
        name: 'fieldsList',
        components: { fieldCell,vuedraggable },
        mixins: [storeVar],
        props: {
            category: {
                default: () => {
                    return 'fields';
                }
            },
            baseProperty: '',
        },
        data () {
            return {
                tableIndex: '0',
                fieldName: '',
                refresh: true,
                fIndex: 0,
                _globalOption: [],
                columns: [
                    {
                        key: 'name',
                        title: this.$t(`compDesign.jProperty.attrName`),
                        minWidth: 90,
                        width: 180,
                        align: 'center'
                    },
                    {
                        key: 'defaultValue',
                        title: this.$t(`compDesign.jProperty.defaultValue`),
                        align: 'center',
                        slot: 'defaultValue'
                    },
                    {
                        key: 'showField',
                        title: this.$t(`compDesign.jProperty.isUse`),
                        width: 100,
                        align: 'center',
                        slot: 'showField'
                    }
                ]
            };
        },
        methods: {
            onSelect(name) {
              this.fIndex = name
            },
            updateRow (index, name, value) {
                if (name === 'type') {
                  if (this.baseProperty 
                    && this.baseProperty !== this.compGroup.currentClassObject.baseProperty
                    && this.compGroup.currentClassObject[this.baseProperty]
                  ) {
                    this.compGroup.currentClassObject[this.baseProperty].changeEditor(index, value)
                  } else {
                    this.compGroup.currentClassObject.changeEditor(index, value)
                  }
                  this.syncGroup();
                  let tableIndex = parseInt(this.tableIndex);
                  // this.$forceUpdate();
                  this.tableIndex = `${tableIndex}`;
                } else {
                    let fieldArr = this.curProperty.fields[index];
                    let nameIndex = fieldArr.findIndex(d => d.name === name);
                    let dataIndex = fieldArr.find(d => d.name === 'dataIndex').defaultValue

                    fieldArr[nameIndex].defaultValue = value;
                    if (['cliEntityTable', 'cliContainerTable'].includes(this.baseProperty)) {
                      this.updateFormRow(index, name, value, 'cliSearchForm', dataIndex);
                      this.updateFormRow(index, name, value, 'cliNewForm', dataIndex);
                      this.updateFormRow(index, name, value, 'cliEditForm', dataIndex);
                      this.updateFormRow(index, name, value, 'cliReadForm', dataIndex);
                    }
                    this.syncGroup();
                    // 当更新optionType，数据会更新但页面不更新，使用$forceUpdate更新不生效，改为refresh触发生命周期更新
                    // 使用两次$nextTick，一次会报错
                    // this.$nextTick(() => {
                    //     this.refresh = false;
                    //     this.$nextTick(() => {
                    //         this.refresh = true;
                    //     })
                    // })
                }
                if (name === 'optionType') {
                  this.compGroup.currentClassObject._setFieldOptionName();
                }
            },
            // 同步四个form表单field
            updateFormRow (index, name, value, propertyKey, dataIndex) {
                let fields = this.compGroup.currentClassObject.property[propertyKey].fields
                
                // search因为不展示非查询字段，所以index对不上，需要重新计算index
                index = fields.findIndex(item => item[1].defaultValue === dataIndex)
                if (index === -1 || !fields || !fields[index]) { return; }
                fields = fields[index]
                let nameIndex = fields.findIndex(d => d.name === name);

                fields && fields[nameIndex] && (fields[nameIndex].defaultValue = value)
            },
            updateFormRow1 (index, name, value) {
                let searchFormFieldArr = this.compGroup.currentClassObject.property['cliSearchForm'].fields[index];
                let newFormFieldArr = this.compGroup.currentClassObject.property['cliNewForm'].fields[index];
                let editFormFieldArr = this.compGroup.currentClassObject.property['cliEditForm'].fields[index];
                let readFormFieldArr = this.compGroup.currentClassObject.property['cliReadForm'].fields[index];
                
                if (!searchFormFieldArr) { return; }
                let nameIndex = searchFormFieldArr.findIndex(d => d.name === name);
                searchFormFieldArr && searchFormFieldArr[nameIndex] && (searchFormFieldArr[nameIndex].defaultValue = value)
                newFormFieldArr[nameIndex].defaultValue = value;
                editFormFieldArr[nameIndex].defaultValue = value;
                readFormFieldArr[nameIndex].defaultValue = value;
            },
            getOptions(config) {
              let options = config.options || []
              if (config.name === 'optionName') {
                options = options.concat(this._globalOption)
              } else if (config.name === 'type') {
                options = filedTypeOption
              } else if (config.name === 'validate') {
                options = ruleTplOption
              } else if (config.sourceKey === 'componentList') {
                options = this.componentList
              } else if (config.sourceKey === 'fields') {
                options = this.curProperty.fields.map(item => {
                  return item.length > 0 ? {label: item[1].defaultValue, value: item[1].defaultValue} : false
                })
              }
              return options
            },
            getFieldLabel(field) {
              let property = this.compGroup.currentClassObject.basePropertyObj;
              let res = '';

              if (field.length > 1) {
                let key = field[1].defaultValue;
                res = key

                if (property && property.international) {
                  let langObj = property.international.find(item => 
                    item.type === 'fields' && (item.value === key || item.name === key)
                  )

                  res = langObj ? (langObj[this.G_Locale] || key) : key
                }
              }
              return res;
            }
        },
        watch: {
          globalOption: {
            handler(val) {
              let _globalOption = []
              
              Object.keys(val).forEach(key => {
                _globalOption.push({label: '全局_' + key, value: key})
              })
              this._globalOption = _globalOption;
            }, immediate: true
          }
        },
        computed: {
          curField() {
            let res = this.curProperty[this.category][this.fIndex] || []

            // console.log("file: fieldsList.vue:196  curField  res:", res)
            return res
          },
          ...mapState('admin/model', [
            'globalOption'
          ]),
          ...mapState('compDesign/config', [
            'modulesTree', //所有组件配置
          ]),
          componentList() {
            let res = []
            this.modulesTree && this.modulesTree.forEach(item => {
              res.push({
                type: item.title,
                label: `分组: ${item.title}` ,
                value: item.title,
                disabled: true
              })
              item.children.forEach(cItem => {
                res.push({
                  type: cItem.title,
                  label: cItem.title,
                  value: cItem.title,
                })
              })
            })
            return res
          },
          // curProperty() {
          //   return this.baseProperty ? this.compGroup.currentItem.property[this.baseProperty] : this.compGroup.currentItem.property
          // }
        },
        mounted () {
          // console.log(this.curProperty[this.category]);
        }
    };
</script>
<style lang="less">
.c-fieldList {
  height: 100%;
  border-top: 1px solid #dcdee2;
  .ivu-table {
    overflow-x: hidden;
    overflow-y: auto;
  }
  .ivu-table-body {
    overflow: hidden;
  }
  .ivu-menu {
    padding: 6px 0;
    min-width: 130px;
    overflow-y: auto;
    border-left: 1px solid #dcdee2;
    border-bottom: 1px solid #dcdee2;
    &::-webkit-scrollbar {
      width: 8px;
    }
  }
  .ivu-menu-item {
    position: relative;
    padding: 12px 6px;
    text-align: left;
    line-height: 1;
    .itemflag {
      position: absolute;
      bottom: 3px;
      left: 6px;
      >span {
        display: inline-block;
        width: 6px;
        height: 6px;
        margin-right: 4px;
        border-radius: 50%;
      }
      .hiddenItem {
        background-color: #aaa;
      }
      .selectItem {
        background-color: var(--primary-color);
      }
      .cusItem {
        background-color: red;
      }
    }
  }
}
</style>
